package com.example.lib_car.applyparking

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewbinding.ViewBinding
import com.alibaba.android.arouter.facade.annotation.Route
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.bigkoo.pickerview.listener.OnTimeSelectListener
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.example.lib_car.ApiService
import com.example.lib_car.adapter.ColorAdapter
import com.example.lib_car.adapter.PicAdapter
import com.example.lib_car.databinding.ActivityApplycarBinding
import com.example.lib_common.mvi.BaseActivity
import com.example.network_sdk.HttpType
import com.example.network_sdk.NetWorkFactory
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import me.shouheng.compress.Compress
import me.shouheng.compress.strategy.Strategies
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import org.greenrobot.eventbus.EventBus
import java.io.File
import java.util.*


@Route(path = "/car/ActivityApplyParking")
class ActivityApplyParking :BaseActivity<ActivityApplycarBinding,ApplyParkingViewModel>(),OnItemClickListener{
    private  var car_uri : ArrayList<Uri> =ArrayList()
    val date = Date()
    var flag = false
    var selColorId =0
    var picAdapter = PicAdapter()
    private var photoPath: String? = null
    private var compressPath: String? = null
    override fun createVM(): ApplyParkingViewModel {
        return ApplyParkingViewModel()
    }

    override fun createViewBinding(): ViewBinding {
        return ActivityApplycarBinding.inflate(inflater)
    }
    var parkId=0
    var parkName =""
    var parkNum : String? =""
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        parkId= intent.getLongExtra("parkId",1).toInt()
        parkName= intent.getStringExtra("parkName").toString()
        parkNum= intent.getStringExtra("parkNum").toString()
        LogUtils.e("==parkName$parkNum")
        if (parkNum!=""&&parkNum!="null"){
            v.carNum.keyListener=null
            flag=true
            v.carNum.setText(parkNum)
        }else{
            v.carNum.setText("")
        }
        var map :HashMap<String,Any> = HashMap()
        map["departmentId"]=SPUtils.getInstance().getInt("dept_id")
        vm.requestDepartment(map)
        convertDate(date,3)
        v.userName.text=SPUtils.getInstance().getString("uName")
        bindState()
        vm.requestColor()
        v.backBtn.setOnClickListener { finish() }
        v.addCar.setOnClickListener { addCarImg() }
        v.startDate.setOnClickListener { pickDate(1) }
        v.endDate.setOnClickListener { pickDate(2) }
        v.carSub.setOnClickListener {
            if (selColorId==0){
                ToastUtils.showShort("未选择车辆颜色")
                return@setOnClickListener
            }
            v.applyparkingRelative.visibility=VISIBLE
            val map = HashMap<String,Any>()
            map["carNum"]=v.carNum.text.toString()
            map["colorId"]=selColorId
            map["parkId"]=parkId
            map["carId"]=parkId
            vm.requestAddCar(map)
        }
    }


    private fun pickDate(type : Int) {
        val endDate = Calendar.getInstance()
        endDate.time=date
        val startDate = Calendar.getInstance()
        startDate.time=date
        endDate.add(Calendar.YEAR,+100)
        val pvTime = TimePickerBuilder(this,object : OnTimeSelectListener{
            override fun onTimeSelect(date1: Date?, view: View?) {
                if (type==1){
                    convertDate(date1,1)
                }else if (type==2){
                    convertDate(date1,2)
                }
            }
        }).setRangDate(startDate, endDate).build()
        pvTime.show()
    }
    var startMonth =0
    var startDate =0
    private fun convertDate(date: Date?, type: Int) {
        val  mCalendar=Calendar.getInstance()
        mCalendar.time=date
        val year = mCalendar.get(Calendar.YEAR)
        val month = mCalendar.get(Calendar.MONTH)
        val day = mCalendar.get(Calendar.DAY_OF_MONTH)
        if (type==1){
            v.startDate.text=""+(month+1)+"月"+day+"日"
            startMonth=month
            startDate=day
        }else if (type==2){
            if (month<startMonth || day<startDate){
                ToastUtils.showShort("结束日期不能小于开始日期")
            }else{
                v.endDate.text=""+(month+1)+"月"+day+"日"
            }
        }else if (type==3){
            v.applyDate.text=""+year+"年"+(month+1)+"月"+day+"日"
        }
    }


    var list:ArrayList<ColorEntity> = ArrayList()
    var belong:ArrayList<DepartmentEntity> = ArrayList()
    private fun bindState() {
        lifecycleScope.launch(Dispatchers.Main){
            repeatOnLifecycle(Lifecycle.State.STARTED){
                vm.mutableContainer.uiStateFlow.collect{
                    if (it.entity.statuesCode==200){
                        list=it.entity.values as ArrayList<ColorEntity>
                        initColor()
                        if (it.entity2.msg=="成功"){
                            belong=it.entity2.values as ArrayList<DepartmentEntity>
                            v.belong.text=belong[0].departmentName
                            SPUtils.getInstance().put("department",belong[0].departmentName)
                        }
                        if (it.entity3.msg == "成功"){
                            val map: HashMap<String, Any> = HashMap()
                            map["carId"] = it.entity3.values.carId
                            map["parkEnd"] = "" + System.currentTimeMillis() / 100
                            map["parkId"] = parkId
                            map["parkName"] = parkName
                            map["parkStart"] = "" + System.currentTimeMillis() / 1000
                            map["parkTime"] = "" + System.currentTimeMillis() / 1000
                            map["parkUser"] = SPUtils.getInstance().getInt("uId")
                            if (flag==true){
                                val intent = Intent()
                                intent.putExtra("statues", "成功")
                                intent.putExtra("parkId",parkId)
                                setResult(123,intent)
                                finish()
                            }else{
                                vm.subParking(map)
                            }
                        }
                        if (it.entity1.msg=="申请成功"){
                            v.applyparkingRelative.visibility = GONE
                            EventBus.getDefault().post("refreshCar")
                            finish()
                        }
                    }
                }
            }
        }

    }

    //================================添加汽图片
    private fun addCarImg() {
        if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.N){
            requestPermissions(arrayOf("android.permission.WRITE_EXTERNAL_STORAGE",
                "android.permission.READ_EXTERNAL_STORAGE"),100)
        }
        val intent = Intent(Intent.ACTION_PICK,null)
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*")
        if (car_uri.size<=6){
            startActivityForResult(intent, 200)
        }else{
            ToastUtils.showShort("最多上传六张")
        }
        if (car_uri.size>0){
            val layoutManager=LinearLayoutManager(this)
            layoutManager.orientation=LinearLayoutManager.HORIZONTAL
            v.applyparkingImgRv.layoutManager=layoutManager
            picAdapter.data=car_uri
            v.applyparkingImgRv.adapter=picAdapter
        }
    }

    @SuppressLint("Range")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode==200){
            if (data!=null){
                var uri : Uri = data.data!!
                LogUtils.e("原图片路径:$uri")
                val cursor = contentResolver.query(
                    uri, arrayOf(MediaStore.Images.Media.DATA),
                    null, null, null
                )
                while (cursor!!.moveToNext()) {
                    photoPath =
                        cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA))
                }
                cursor.close() //防止内存泄露
                compress()
                car_uri.add(uri)
                picAdapter.notifyDataSetChanged()
            }
        }
    }

    private fun compress() {
        var file=File(photoPath)
        lifecycleScope.launch(Dispatchers.IO){
            var compress = Compress.with(this@ActivityApplyParking, file)
                .strategy(Strategies.luban())
                .setIgnoreSize(100,true)
                .get()
//            vm.requestUpLoadImg(get.path)
            val requestBody = RequestBody.create(MediaType.parse("multipart/form-data"),compress)
            val imgpart = MultipartBody.Builder().addFormDataPart("file",compress.name,requestBody).build().parts()
            NetWorkFactory.factory(HttpType.NONE)!!
                .create(ApiService::class.java)
                .uploadIms(imgpart)
                .collect{
                    launch (Dispatchers.Main){
                        println("==========${it.msg}")
                    }
                }
        }
    }


    private fun initColor() {
        val colorAdapter =ColorAdapter()
        val layoutManager=LinearLayoutManager(this)
        layoutManager.orientation=LinearLayoutManager.HORIZONTAL
        v.applyparkingRv.layoutManager=layoutManager
        colorAdapter.data=list
        v.applyparkingRv.adapter=colorAdapter
        colorAdapter.setOnItemClickListener(this)
    }

    override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
       var list : ArrayList<ColorEntity> = adapter.data as ArrayList<ColorEntity>
        selColorId= list[position].colorId.toInt()
        v.carColor.setBackgroundColor(Color.parseColor(list[position].colorValue))
    }
}